﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GONES.IBLL;
using GONES.IDAL;
using GONES.Model;
using log4net;
using System.Reflection;
using Newtonsoft.Json;
using GONES.Tools.Common;
using System.Collections;

namespace GONES.BLL
{
    public class S_UsersManager : IS_UsersManager
    {
        protected static readonly ILog Log =
                LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private readonly IUserInfo _userInfo;
        public IS_UsersDao S_UsersDao;
        public IS_LogDao S_LogDao;
        public S_LogManager S_LogManager;
        public string ErrMsg { get; set; }

        public S_UsersManager(IUserInfo userinfo)
        {
            _userInfo = userinfo;
        }

        public S_Users Get(string id)
        {
            return S_UsersDao.Get(id);
        }

        /// <summary>
        /// 新增用户信息
        /// </summary>
        /// <param name="users">用户信息</param>
        public void Add(S_Users users)
        {
            if (IsError(users))
                return;
            users.CreateTime = System.DateTime.Now;
            S_UsersDao.Save(users);
            SaveLog("用户信息", "用户添加", "系统管理", users);
           
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="users">用户信息</param>
        public void Edit(S_Users users)
        {
            users.ModifyTime = System.DateTime.Now;
            S_UsersDao.Update(users);
            SaveLog("用户信息", "用户修改", "系统管理", users);
        }

        /// <summary>
        /// 删除用户信息
        /// </summary>
        /// <param name="id">用户ID</param>
        public void Delete(string id)
        {
            S_Users users = S_UsersDao.Get(id);
            S_UsersDao.Delete(users);
            SaveLog("用户信息", "用户删除", "系统管理", users);
        }

        /// <summary>
        /// 用户验证
        /// </summary>
        /// <param name="loginname">登陆用户名称</param>
        /// <param name="loginpass">登陆用户密码</param>
        /// <returns>登陆用户信息</returns>
        public LoginInfo Login(string loginname, string loginpass)
        {
            if (Log.IsDebugEnabled)
                Log.Debug(string.Format("用户登陆 登陆名为 {0} 密码为 {1}", loginname, loginpass));
            var logininfo = new LoginInfo();
            IList<S_Users> s_users;
            s_users = S_UsersDao.GetList().Where(u => u.UserName == loginname).ToList();
            if (s_users.Count == 0)
            {
                ErrMsg = "用户名不存在！";
                return logininfo;
            }
            if (s_users[0].UserPassWord != (loginpass.Length == 32 ? loginpass : Rnd.MD5(Rnd.MD5(loginpass))))
            {
                ErrMsg = "密码不正确，请检查！";
                return logininfo;
            }
            S_Users user = s_users[0];
            if(user.IsDisabled ==1)
            {
                ErrMsg = "该用户暂时无法登陆，已被禁用，请联系系统管理员处理!";
                return logininfo;
            }
            if (user.IsDeleted == 1)
            {
                ErrMsg = "该用户暂时无法使用，已被删除，请联系系统管理员处理!";
                return logininfo;
            }
            logininfo.UserId = user.ID;
            logininfo.UserName = user.UserName;
            logininfo.UserPassWord = user.UserPassWord;
            logininfo.LoginIp = Tools.Common.Tools.GetIP();
            logininfo.LoginCount = user.LoginCount;
            logininfo.LastLoginTime = user.LastLoginTime;

            user.LoginCount += 1;
            user.LastLoginTime = DateTime.Now;
            S_UsersDao.Update(user);
            SaveLog("用户信息", "用户登陆", "系统管理", user);
            return logininfo;
        }

        /// <summary>
        ///  找回密码验证
        /// </summary>
        /// <param name="loginid">用户ID</param>
        /// <param name="tel">手机号</param>
        /// <param name="users">用户信息</param>
        /// <returns>验证结果</returns>
        public bool CheckUser(string loginid, string tel, ref S_Users users)
        {
            if (Log.IsDebugEnabled)
                Log.Debug(string.Format("用户找回密码验证 登陆ID为 {0} 手机为 {1}", loginid, tel));

            var loginInfo = new LoginInfo();
            IList<S_Users> userInfos =
                S_UsersDao.GetList().Where(u => u.ID == loginid).ToList();

            if (userInfos.Count == 0)
            {
                ErrMsg = "用户不存在";
                return false;
            }
            users = userInfos[0];
            SaveLog("用户信息", "找回密码验证", "系统管理", users);
            return true;
        }

        /// <summary>
        /// 更改用户密码
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <param name="oldpass">原密码</param>
        /// <param name="newpass">新密码</param>
        public  void ChangePassWord(string id,string oldpass,string newpass)
        {
            S_Users userinfo = S_UsersDao.Get(id);
            if (Rnd.MD5(Rnd.MD5(oldpass)) != userinfo.UserPassWord)
            {
                ErrMsg = "旧密码不正确";
                return;
            }

            userinfo.UserPassWord = newpass.Length == 32 ? newpass : Rnd.MD5(Rnd.MD5(newpass));
            userinfo.ModifyUser = _userInfo.CLoginInfo.UserName;
            userinfo.ModifyTime = DateTime.Now;
            S_UsersDao.Update(userinfo);
            SaveLog("用户信息", "用户修改密码", "系统管理", userinfo);
        }

        /// <summary>
        /// 更改用户登陆名
        /// </summary>
        /// <param name="oldloginname">原用户名</param>
        /// <param name="newloginname">新用户名</param>
        public void ChangeLoginName(string oldloginname, string newloginname)
        {
            S_Users userinfo = S_UsersDao.GetList().Where(u => u.UserName == oldloginname).FirstOrDefault();
            if (userinfo == null)
            {
                ErrMsg = "用户名不存在！";
                return;
            }
            if (S_UsersDao.GetList().Where(u => u.UserName == newloginname).Count() > 0)
            {
                ErrMsg = "用户名被暂用，请更换！";
                return;
            }
            userinfo.UserName = newloginname;
            userinfo.ModifyUser = _userInfo.CLoginInfo.UserName;
            userinfo.ModifyTime = DateTime.Now;
            S_UsersDao.Update(userinfo);
            SaveLog("用户信息", "修改用户名", "系统管理", userinfo);
        }

        /// <summary>
        /// 用户密码重置
        /// </summary>
        /// <param name="id">用户ID</param>
        public void ResetPassWord(string id)
        {
            S_Users userinfo = S_UsersDao.Get(id);
            userinfo.UserPassWord = GlobalSettings.Instance.DefaultPassWord.Length == 32
                                     ? GlobalSettings.Instance.DefaultPassWord
                                     : Rnd.MD5(Rnd.MD5(GlobalSettings.Instance.DefaultPassWord));
            userinfo.ModifyUser = _userInfo.CLoginInfo.UserName;
            userinfo.ModifyTime = DateTime.Now;
            S_UsersDao.Update(userinfo);
            SaveLog( "用户信息", "用户密码重置","系统管理",userinfo);
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="filters">条件</param>
        /// <param name="pageIndex">页号</param>
        /// <param name="pageSize">每页条数</param>
        /// <param name="recordCount">记录条数</param>
        /// <returns>用户列表</returns>
        public IList<S_Users> List(IList<DataFilter> filters, int pageIndex, int pageSize, ref long recordCount)
        {
            string strFilter = DataOperate.GetHqlstrByExtFilter(filters, "e");
             recordCount = S_UsersDao.ExecHqlResultLong("SELECT COUNT(*) FROM S_Users e WHERE 1=1 " +
                                                  (string.IsNullOrEmpty(strFilter) ? string.Empty : " AND " + strFilter));

            return S_UsersDao.GetHqlList("SELECT e FROM S_Users e WHERE 1=1 " +
                                          (string.IsNullOrEmpty(strFilter)
                                               ? string.Empty
                                               : " AND " + strFilter) + " ORDER BY e.ID DESC", (pageIndex - 1) * pageSize,
                                          pageSize);
        }


        /// <summary>
        /// 获取指定部门下的用户数
        /// </summary>
        /// <param name="departid">部门ID</param>
        /// <returns>用户数量</returns>
        public long GetUserCount(string departid)
        {
            long num =
                S_UsersDao.ExecHqlResultLong(string.Format("SELECT COUNT(*) FROM S_Users e WHERE e.departid = {0}", departid));
            return num;
        }


        private void SaveLog(string module, string operate, string logtype, S_Users users)
        {
            S_LogManager = new S_LogManager(_userInfo);
            string detail = string.Format("{0}:用户名是{1}", operate, users.UserName);
           SaveLog(module, operate, logtype, detail);
            if (Log.IsInfoEnabled)
                Log.Info(string.Format("{0}：{1}", operate, JsonConvert.SerializeObject(users)));
        }

        protected bool IsError(S_Users user)
        {
            if (string.IsNullOrEmpty(user.UserName))
            {
                ErrMsg = "用户名不能为空！";
            }
            else if (S_UsersDao.GetList().Where(g => g.UserName == user.UserName).Count() > 0)
            {
                ErrMsg = "该用户名已经存在！";
            }
            if (!string.IsNullOrEmpty(ErrMsg))
                return true;
            return false;
        }

        /// <summary>
        /// 保存日志
        /// </summary>
        /// <param name="module">模块名称</param>
        /// <param name="operate">操作名称</param>
        /// <param name="logtype">日志类型（系统管理、基础资料等）</param>
        /// <param name="detail">详细日志</param>
        protected void SaveLog(string module, string operate, string logtype, string detail)
        {
            try
            {
                S_LogDao.Save(new S_Log
                {
                    ID = Rnd.Guid.ToString(),
                    Module = module,
                    Operate = operate,
                    Detail = detail,
                    LogType = logtype,
                    OpDate = DateTime.Now,
                    CreateUser = _userInfo.CLoginInfo.UserName,
                    CreateTime = DateTime.Now,
                    ModifyUser = _userInfo.CLoginInfo.UserName,
                    ModifyTime = DateTime.Now,
                    Ip = Tools.Common.Tools.GetIP()
                });
            }
            catch
            {
            }
        }
    }
}
